<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Api\WechatController;
use App\Models\XcUser;
use App\Models\XcUserConsumerDetails;
use App\Models\XcUserRecharge;
use Illuminate\Support\Facades\Redis;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;

class RechargeOrderController extends Controller
{

    /**
     * 列表
     *
     * @return \Illuminate\Contracts\View\View
     */
    public function index()
    {
        return View::make('admin.rechargeOrder.index');
    }

    /**
     * 分页数据
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function data(Request $request)
    {
        $data = $request->all();

        $query = XcUserRecharge::query();

        if (!empty($data['pay_status'])) {
            $query->where('pay_status', '=', $data['pay_status']);
        } else {
            $query->where('pay_status', '>', 1);
        }

        if (!empty($data['order_sn'])) {
            $query->where('order_sn', 'LIKE', "%" . $data['order_sn'] . "%");
        }

        if (!empty($data['pay_time_beg'])) {
            $query->where('pay_time', '>=', $data['pay_time_beg'] . ' 00:00:00');
        }

        if (!empty($data['pay_time_end'])) {
            $query->where('pay_time', '<=', $data['pay_time_end'] . ' 23:59:59');
        }

        $res = $query->with('user')->whereHas('user', function ($userQuery) use ($data) {
            if (!empty($data['mobile'])) {
                $userQuery->where('mobile', 'LIKE', "%" . $data['mobile'] . "%");
            }
        })->orderBy('id', 'desc')->paginate($request->get('limit', 10))->toArray();

        foreach ($res['data'] as &$val) {
            $val['pay_status_text'] = $val['status'] == 4 ? '已退款' : ($val['status'] == 3 ? '已完成' : ($val['status'] == 2 ? '已支付' : '未支付'));
            $val['mobile'] = isset($res['user']['mobile']) ? $res['user']['mobile'] : '';
        }

        $data = [
            'code' => 0,
            'msg' => '正在请求中...',
            'count' => $res['total'],
            'data' => $res['data'],
        ];

        return Response::json($data);
    }

    /**
     * 退款表单
     *
     */
    public function refundform(Request $request)
    {
        $id = $request->get("id");
        $order = XcUserRecharge::where('id', '=', $id)->first()->toArray();

        return View::make('admin.rechargeOrder.refund', compact('order'));
    }

    /**
     * 会员卡、次卡退款
     * @param Request $request
     */
    public function refund(Request $request)
    {
        $this->validate($request, [
            'id' => 'required',
            'suggest_refund_amount' => 'required',
            'refund_amount' => 'required',
            'refund_remark' => 'required|string',
        ]);

        $data = $request->all();

        $order = XcUserRecharge::where('id', $data['id'])->first();

        if (!in_array($order->type, [2, 3, 4, 5])) {
            return jsonReturn([], -1, '该订单类型不支持单笔订单退款，请前往用户中心');
        }

        if ($order->status != 2) {
            return jsonReturn([], -1, '该订单状态不支持退款');
        }

        $day = date('Y-m-d');

        if ($order->end_time <= $day) {
            return jsonReturn([], -1, '该卡使用时间已过期，不支持退款');
        }

        $weChat = new WechatController();

        $result = $weChat->refund($order->order_sn, $weChat->OrderSN('RF'), $data['refund_amount'], "《{$order->recharge_name}》订单退款");

        if (isset($result['result_code']) && $result['result_code'] == 'FAIL') {
            return jsonReturn([], -1, $result['err_code_des']);
        }

        DB::beginTransaction();
        try {
            $update = [
                'pay_status' => 3,
                'status' => 4,
                'refund_id' => $result['refund_id'],
                'refund_no' => $result['out_refund_no'],
                'refund_time' => date('Y-m-d H:m:s'),
                'suggest_refund_amount' => $data['suggest_refund_amount'],
                'refund_amount' => $data['refund_amount'],
                'refund_worker' => Auth::user()->nickname,
                'refund_remark' => $data['refund_remark']
            ];

            $order->update($update);

            //次卡订单退款
            if ($order->type == 5) {

                //剩余未使用完的次卡过期

                //快洗未使用完成过期记录
                $num = $order->fast_washing_num - $order->used_fast_washing_num;

                $num > 0 ? (new XcUserConsumerDetails())->changeLog($order->user_id, $num, 6, $order->order_sn, 3, '', 0, 1) : '';

                //精洗未使用完成过期记录
                $num = $order->fine_washing_num - $order->used_fine_washing_num;

                $num > 0 ? (new XcUserConsumerDetails())->changeLog($order->user_id, $num, 6, $order->order_sn, 3, '', 0, 2) : '';
            } else {

                //更新会员卡信息有效期，将user表里会员卡过期时间修正为最新的，如果是中间的卡退款，后续的卡的有效期均要往前挪动

                $user = XcUser::where('id', $order->user_id)->first();

                $start_time = $order->start_time > $day ? $order->start_time : $day;

                //需要减去过期天数
                $expire_day = date_diff(date_create($order->end_time), date_create($start_time))->format('%a');

                //1/2：快洗/精洗
                if ($order->fast_washing_num == 1) {
                    $field = 'fast_member_exp';
                    $exp_now = $user->fast_member_exp;
                } else {
                    $field = 'fine_member_exp';
                    $exp_now = $user->fine_member_exp;
                }

                $member_exp = date('Y-m-d', strtotime("-{$expire_day} day", strtotime($exp_now)));

                $user->update(["{$field}" => $member_exp]);

                //如取消的卡后面还有卡，则将所有有效期提前
                if ($exp_now != $order->end_time) {
                    XcUserRecharge::where('id', '>', $order->id)->whereIn('type', [2, 3, 4])->where('user_id', $order->user_id)->where('status', 2)->update([
                        'start_time' => DB::raw("DATE_SUB(start_time , INTERVAL {$expire_day} DAY)"),
                        'end_time' => DB::raw("DATE_SUB(end_time , INTERVAL {$expire_day} DAY)"),
                    ]);
                }
            }

            DB::commit();
            return jsonReturn();
        } catch (\Exception $exception) {
            DB::rollback();
            return jsonReturn([], -1, $exception->getMessage());
        }

    }
}